#include "widget.h"
#include "ui_widget.h"

void Init_Sql();
float A_temprature_value_show=30;
float A_comgas_value_show=30;
float A_flame_value_show=30;
float A_shake_value_show=30;
float A_light_value_show=30;

float B_temprature_value_show=30;
float B_comgas_value_show=30;
float B_flame_value_show=30;
float B_shake_value_show=30;
float B_light_value_show=30;

float C_temprature_value_show=30;
float C_comgas_value_show=30;
float C_flame_value_show=30;
float C_shake_value_show=30;
float C_light_value_show=30;

int A_temprature_get_lora=25;
int A_comgas_get_lora=25;
int A_flame_get_lora=25;
int A_shake_get_lora=25;
int A_light_get_lora=25;
int B_temprature_get_lora=25;
int B_comgas_get_lora=25;
int B_flame_get_lora=25;
int B_shake_get_lora=25;
int B_light_get_lora=25;
int C_temprature_get_lora=25;
int C_comgas_get_lora=25;
int C_flame_get_lora=25;
int C_shake_get_lora=25;
int C_light_get_lora=25;

int index1=0,index2=0,index3=0;
int inserSQL_order=1;

bool Net_work_flag;
bool onoff_jiedian_1,onoff_jiedian_2,onoff_jiedian_3;

int shuzi_tiaozheng_index1=0;

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
        ui->setupUi(this);

     back_color_set();






        Net_work_flag=0;
        Net_work_flag=init_mqtt();
        timer_canshu = new QTimer(this);
        connect(timer_canshu, SIGNAL(timeout()), this, SLOT(timer_task1_showcan()));
        timer_canshu->start(200);                // 1秒钟触发一次

        timer = new QTimer(this);
        connect(timer, SIGNAL(timeout()), this, SLOT(timer_networkonoff_task()));
        timer->start(1000); // 1秒钟触发一次

        this->mychart_record=new chart;
        connect(this->mychart_record,SIGNAL(back()),this,SLOT(comeBackToPrev()));

        Init_Lora();        
        Init_4G();
        Init_Sql();
        Lora_Read_all();
}




void Widget::comeBackToPrev()
{
    this->mychart_record->hide();
    this->show();
}

void Widget::back_color_set()
{
    //back_jie1
    //textEdit_5
    ui->label_38->setStyleSheet(
        "QLabel {"
        "background: qlineargradient(spread:pad, x1:0, y1:0, x2:1, y2:1,"
                "stop:0 rgba(200,230,255,120), stop:1 rgba(160,210,255,160));"

        "}"
    );

//    QGraphicsDropShadowEffect *effect = new QGraphicsDropShadowEffect;
//    effect->setBlurRadius(15);
//    effect->setOffset(2, 2);
//    effect->setColor(QColor(0, 0, 0, 100));
//    ui->back_jie1->setGraphicsEffect(effect);



    ui->back_jie1->setStyleSheet(
        "QTextEdit {"
        "background: qlineargradient(x1:1, y1:0, x2:0, y2:1, "
        "stop:0 rgba(180,240,255,150), stop:1 rgba(130,200,250,200));"
        "border-radius: 8px;"
        "}"
    );


    ui->textEdit_5->setStyleSheet(
        "QTextEdit {"
        "background: qlineargradient(x1:0, y1:1, x2:1, y2:0, "
        "stop:0 rgba(190,220,235,130), stop:1 rgba(100,180,240,180));"
        "border-radius: 8px;"
        "}"
    );




}


void Widget::timer_networkonoff_task()
{
    Net_work_flag = isNetWorkOnline();
    ui->Net_work_show->setReadOnly(true);
    ui->Net_work_show->clear();
    //QString text = QString::fromUtf8(msg_data);
    if(Net_work_flag){
        QString net_pasa = "已连接";
        ui->Net_work_show->setText(net_pasa);
    }
    else{
        QString net_pasa = "已断开";
        ui->Net_work_show->setText(net_pasa);
    }
}

//将接收到的数据显示在界面上
void Widget::timer_task1_showcan()
{

   int randNumber = QRandomGenerator::global()->bounded(100);
   if(inserSQL_order==1)
   {

     A_temprature_value_show=A_temprature_get_lora/4096.0*3.3*100;
     A_comgas_value_show=(A_comgas_get_lora/4096.0)*100*10+randNumber/100.0;
     A_flame_value_show=(1.0-A_flame_get_lora/4096.0)*100+randNumber/100.0;
     A_shake_value_show=A_shake_get_lora/4096.0*330+randNumber/100.0;
     A_light_value_show=500-0.1197*A_light_get_lora;

     my_InsertSQL(1);
     if(onoff_jiedian_1==1)
     {
         ui->temputer_1->setText(QString::number(A_temprature_value_show, 'f', 2));
         ui->comgas_1->setText(QString::number(A_comgas_value_show, 'f', 2));
         ui->flame_1->setText(QString::number(A_flame_value_show, 'f', 2));
         ui->shake_1->setText(QString::number(A_shake_value_show, 'f', 2));
         ui->light_1->setText(QString::number(A_light_value_show, 'f', 2));
     }

   }

   else if(inserSQL_order==2)
   {

       B_temprature_value_show=B_temprature_get_lora/4096.0*3.3*100;
       B_comgas_value_show=(B_comgas_get_lora/4096.0)*100*10+randNumber/100.0;
       B_flame_value_show=(1.0-B_flame_get_lora/4096.0)*100+randNumber/100.0;
       B_shake_value_show=B_shake_get_lora/4096.0*330+randNumber/100.0;
       B_light_value_show=500-0.1197*B_light_get_lora;

     my_InsertSQL(2);
     if(onoff_jiedian_2==1)
     {
         ui->temputer_2->setText(QString::number(B_temprature_value_show, 'f', 2));
         ui->comgas_2->setText(QString::number(B_comgas_value_show, 'f', 2));
         ui->flame_2->setText(QString::number(B_flame_value_show, 'f', 2));
         ui->shake_2->setText(QString::number(B_shake_value_show, 'f', 2));
         ui->light_2->setText(QString::number(B_light_value_show, 'f', 2));
     }

   }

   else if(inserSQL_order==3)
   {
       C_temprature_value_show=A_temprature_get_lora/4096.0*3.3*100+randNumber/100.0;
       C_comgas_value_show=(C_comgas_get_lora/4096.0)*100*10+randNumber/100.0;
       C_flame_value_show=(1.0-C_flame_get_lora/4096.0)*100+randNumber/100.0;
       C_shake_value_show=C_shake_get_lora/4096.0*330+randNumber/100.0;
       C_light_value_show=500-0.1197*C_light_get_lora;

     my_InsertSQL(3);
     if(onoff_jiedian_3==1)
     {
         ui->temputer_3->setText(QString::number(C_temprature_value_show, 'f', 2));
         ui->comgas_3->setText(QString::number(C_comgas_value_show, 'f', 2));
         ui->flame_3->setText(QString::number(C_flame_value_show, 'f', 2));
         ui->shake_3->setText(QString::number(C_shake_value_show, 'f', 2));
          ui->light_3->setText(QString::number(C_light_value_show, 'f', 2));
     }
   }

   if(++inserSQL_order>=4)  inserSQL_order=1;
}

//4G串口的初始化
void Widget::Init_4G()
{
    m4G_serial.setPortName(USB_4G); // 或你自己的串口名
    m4G_serial.setBaudRate(QSerialPort::Baud19200);
    m4G_serial.setDataBits(QSerialPort::Data8);
    m4G_serial.setParity(QSerialPort::NoParity);
    m4G_serial.setStopBits(QSerialPort::OneStop);
    m4G_serial.setFlowControl(QSerialPort::NoFlowControl);

    if (!m4G_serial.open(QIODevice::ReadWrite)) //(!m_serial.open(QIODevice::ReadWrite))
    {
        qDebug() << "打开4G串口失败:" << m4G_serial.errorString();
        return;
    }
}

//4G发送信息
void Widget::Send_4G_message(const QByteArray &message)
{
    if (!m4G_serial.isOpen()) {
        qDebug() << "串口4G未打开，无法发送数据";
        return;
    }

    qint64 bytesWritten = m4G_serial.write(message);
    if (bytesWritten == -1) {
        qDebug() << "Failed to write data to port" << USB_4G << ", error:" << m4G_serial.errorString();
        return;
    }

    // 等待写入完成
    if (!m4G_serial.waitForBytesWritten(1000)) { // 最多等 1 秒
        qDebug() << "Timeout waiting for bytes to be written.";
    }

    QThread::msleep(500); // 推荐使用 Qt 的非整数 sleep（0.5 秒）
}



//lora串口的初始化
void  Widget::Init_Lora()
{
       mlora_serial.setPortName(USB_Lora); // 或你自己的串口名
       mlora_serial.setBaudRate(QSerialPort::Baud19200);
       mlora_serial.setDataBits(QSerialPort::Data8);
       mlora_serial.setParity(QSerialPort::NoParity);
       mlora_serial.setStopBits(QSerialPort::OneStop);
       mlora_serial.setFlowControl(QSerialPort::NoFlowControl);

       if (!mlora_serial.open(QIODevice::ReadWrite)) //
       {
           qDebug() << "打开LORA串口失败:" << mlora_serial.errorString();
           return;
       }
       connect(&mlora_serial, &QSerialPort::readyRead, this, &Widget::Lora_Read_all);
}


//lora串口接收数据进行处理
void Widget::Lora_Read_all()
{
     static QByteArray buffer;
     QByteArray data = mlora_serial.readAll();
      qDebug() << "打开:" << data;
      buffer.append(data);
     if(!data.isEmpty())
     {
              int index;
              while ((index = buffer.indexOf("\r\n")) != -1)  // 找到一帧结束符
              {
                  QByteArray frame = buffer.left(index + 2);  // 提取完整帧（包含\r\n）
                  buffer.remove(0, index + 2);                // 移除已处理部分

                  if (frame.size() >= 8)
                  {
                      QString header = frame.mid(0, 4);
                      QString valueStr = frame.mid(4, 4);
                      int value = valueStr.toInt();

                      if (value != 9999 && value != 0)
                      {
                          if (header == "0A01")
                          {
                               A_temprature_get_lora = value;

                          }

                          else if (header == "0A02")
                          {
                            A_comgas_get_lora = value;

                          }

                          if (header == "0A03")
                          {
                            A_flame_get_lora= value;

                          }

                          else if (header == "0A04")
                          {
                             A_shake_get_lora = value;

                          }

                          else if (header == "0A05")
                          {
                             A_light_get_lora = value;

                          }

                          if (header == "0B01")
                          {
                            B_temprature_get_lora = value;
                            B_temprature_value_show=B_temprature_get_lora;
                          }
                          else if (header == "0B02")
                          {
                            B_comgas_get_lora = value;
                            B_comgas_value_show=B_comgas_get_lora;
                          }
                          if (header == "0B03")
                          {
                            B_flame_get_lora= value;
                            B_flame_value_show=B_flame_get_lora;
                          }
                          else if (header == "0B04")
                          {
                            B_shake_get_lora = value;
                            B_shake_value_show=B_shake_get_lora;
                          }

                          else if (header == "0B05")
                          {
                             B_light_get_lora = value;
                             B_light_value_show=B_light_get_lora;
                          }

                          if (header == "0C01")
                          {
                            C_temprature_get_lora = value;
                            C_temprature_value_show=C_temprature_get_lora;
                          }

                          else if (header == "0C02")
                          {
                             C_comgas_get_lora = value;
                             C_comgas_value_show=C_comgas_get_lora;
                          }

                          if (header == "0C03")
                          {
                            C_flame_get_lora= value;
                            C_flame_value_show=C_flame_get_lora;
                          }

                          else if (header == "0C04")
                          {
                            C_shake_get_lora = value;
                            C_shake_value_show=C_shake_get_lora;
                          }

                          else if (header == "0C05")
                          {
                             C_light_get_lora = value;
                             C_light_value_show=C_light_get_lora;
                          }


                      }
                  }
               }
     }



}


void Widget::my_InsertSQL(int8_t zd_name)
{

  QString connName = "qt_sql_default_connection";
  if (QSqlDatabase::contains(connName)) {
         QSqlDatabase::removeDatabase(connName);
     }
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", connName);
    db.setDatabaseName("lyshark.db");

    if (!db.open())
    {
        std::cout << db.lastError().text().toStdString()<< std::endl;
        return;
    }

    QDateTime curDateTime = QDateTime::currentDateTime();//获取时间
    QString date_time = curDateTime.toString("yyyy-MM-dd hh:mm:ss");//获取时间

        if(1==zd_name)
        {
            float temprature_value  =A_temprature_value_show;
            float comgas_value      =A_comgas_value_show;
            float flame_value       =A_flame_value_show;
            float shake_value       =A_shake_value_show;
            float light_value       =A_light_value_show;
            QString msg_db=QString ("{\"id\":%1,\"zd_id\":%2,\"datetime\":\"%3\",\"temperature\":%4,\"comgas\":%5,\"flame\":%6,\"shake\":%7,\"light\":%8}")
                    .arg(index1).arg(zd_name).arg(date_time).arg(temprature_value).arg(comgas_value).arg(flame_value).arg(shake_value).arg(light_value);
           QTextCodec *codec = QTextCodec::codecForName("GBK");
           QByteArray fs_data = codec->fromUnicode(msg_db);
           if(Net_work_flag)
           {
               uint8_t *msg = (uint8_t *)fs_data.constData();
               size_t length = strlen((char *)msg);
               aiot_mqtt_pub(mqtt_handle, "/k16xk8aneqk/mqtt_loong/user/update", msg,length,0);
           }
           else {
               Send_4G_message(fs_data);
           }

          //  qDebug() << "4G数据_A:" << fs_data;

                QString run_sql = QString("INSERT INTO Times1(id,zd_name,datetime,temprature,comgas,flame,shake,light) VALUES (%1,%2,'%3',%4,%5,%6,%7,%8);")
                        .arg(index1).arg(zd_name).arg(date_time).arg(temprature_value).arg(comgas_value).arg(flame_value).arg(shake_value).arg(light_value);
               std::cout << "执行插入语句: " << run_sql.toStdString() << std::endl;
                qDebug() << "\n";
                index1++;
                db.exec(run_sql);
        }

        else if(2==zd_name)
        {
            float temprature_value  =B_temprature_value_show;
            float comgas_value      =B_comgas_value_show;
            float flame_value       =B_flame_value_show;
            float shake_value       =B_shake_value_show;
            float light_value       =B_light_value_show;
            QString msg_db=QString ("{\"id\":%1,\"zd_id\":%2,\"datetime\":\"%3\",\"temperature\":%4,\"comgas\":%5,\"flame\":%6,\"shake\":%7,\"light\":%8}")
                    .arg(index2).arg(zd_name).arg(date_time).arg(temprature_value).arg(comgas_value).arg(flame_value).arg(shake_value).arg(light_value);
           QTextCodec *codec = QTextCodec::codecForName("GBK");
           QByteArray fs_data = codec->fromUnicode(msg_db);
           if(Net_work_flag)
           {
               uint8_t *msg = (uint8_t *)fs_data.constData();
               size_t length = strlen((char *)msg);
               aiot_mqtt_pub(mqtt_handle, "/k16xk8aneqk/mqtt_loong/user/update", msg,length,0);
           }
           else {
               Send_4G_message(fs_data);
           }

                QString run_sql = QString("INSERT INTO Times2(id,zd_name,datetime,temprature,comgas,flame,shake,light) VALUES (%1,%2,'%3',%4,%5,%6,%7,%8);")
                        .arg(index2).arg(zd_name).arg(date_time).arg(temprature_value).arg(comgas_value).arg(flame_value).arg(shake_value).arg(light_value);
                std::cout << "执行插入语句: " << run_sql.toStdString() << std::endl;
                qDebug() << "\n";
                index2++;
                db.exec(run_sql);
        }

        else if(3==zd_name)
        {
            float temprature_value  =C_temprature_value_show;
            float comgas_value      =C_comgas_value_show;
            float flame_value       =C_flame_value_show;
            float shake_value       =C_shake_value_show;
            float light_value       =C_light_value_show;
            QString msg_db=QString ("{\"id\":%1,\"zd_id\":%2,\"datetime\":\"%3\",\"temperature\":%4,\"comgas\":%5,\"flame\":%6,\"shake\":%7,\"light\":%8}")
                    .arg(index3).arg(zd_name).arg(date_time).arg(temprature_value).arg(comgas_value).arg(flame_value).arg(shake_value).arg(light_value);
           QTextCodec *codec = QTextCodec::codecForName("GBK");
           QByteArray fs_data = codec->fromUnicode(msg_db);
           if(Net_work_flag)
           {
               uint8_t *msg = (uint8_t *)fs_data.constData();
               size_t length = strlen((char *)msg);
               aiot_mqtt_pub(mqtt_handle, "/k16xk8aneqk/mqtt_loong/user/update", msg,length,0);
           }
           else {
               Send_4G_message(fs_data);
           }

                QString run_sql = QString("INSERT INTO Times3(id,zd_name,datetime,temprature,comgas,flame,shake,light) VALUES (%1,%2,'%3',%4,%5,%6,%7,%8);")
                        .arg(index3).arg(zd_name).arg(date_time).arg(temprature_value).arg(comgas_value).arg(flame_value).arg(shake_value).arg(light_value);
                std::cout << "执行插入语句: " << run_sql.toStdString() << std::endl;
                qDebug() << "\n";
                index3++;
                db.exec(run_sql);
        }
        db.commit();
        db.close();
}

void Widget::on_open_jie_button_clicked()
{
    if(ui->comboBox->currentText()=="节点1"){
        onoff_jiedian_1=1;
    }
    else if(ui->comboBox->currentText()=="节点2"){
        onoff_jiedian_2=1;
    }
    else if(ui->comboBox->currentText()=="节点3"){
        onoff_jiedian_3=1;
    }
}


void Widget::on_close_jie_button_clicked()
{
    if(ui->comboBox->currentText()=="节点1"){
        onoff_jiedian_1=0;
    }
    else if(ui->comboBox->currentText()=="节点2"){
        onoff_jiedian_2=0;
    }
    else if(ui->comboBox->currentText()=="节点3"){
        onoff_jiedian_3=0;
    }
}

void Widget::on_open_all_button_clicked()
{
    onoff_jiedian_1=1;
    onoff_jiedian_2=1;
    onoff_jiedian_3=1;
}

void Widget::on_Goto_page_button_clicked()
{
    this->close();
    this->mychart_record->show();
}

Widget::~Widget()
{
    delete ui;
}


void Init_Sql()
{
    // 删除默认连接
    if (QSqlDatabase::contains("qt_sql_default_connection")) {
        QSqlDatabase::removeDatabase("qt_sql_default_connection");
    }

    // 创建新的数据库连接
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("lyshark.db");

    if (!db.open())
    {
        std::cout << db.lastError().text().toStdString() << std::endl;
        return;
    }

    // 创建表的SQL语句
    QString createTableSQL = "CREATE TABLE %1 ("
                             "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                             "zd_name INTEGER NOT NULL, "
                             "datetime VARCHAR(128) NOT NULL, "
                             "temprature INTEGER NOT NULL,"
                             "comgas INTEGER NOT NULL,"
                             "flame INTEGER NOT NULL,"
                             "shake INTEGER NOT NULL,"
                             "light INTEGER NOT NULL"
                             ")";

////        // 删除并创建Times1表
//         db.exec("DROP TABLE IF EXISTS Times1");
//         db.exec(createTableSQL.arg("Times1"));

////        // 删除并创建Times2表
//        db.exec("DROP TABLE IF EXISTS Times2");
//        db.exec(createTableSQL.arg("Times2"));

////        // 删除并创建Times3表
//        db.exec("DROP TABLE IF EXISTS Times3");
//        db.exec(createTableSQL.arg("Times3"));

    // 检查并创建Times1表
    db.exec(createTableSQL.arg("Times1"));

    // 检查并创建Times2表
    db.exec(createTableSQL.arg("Times2"));

    // 检查并创建Times3表
    db.exec(createTableSQL.arg("Times3"));


    QSqlQuery query;
    query.exec("SELECT MAX(id) FROM Times1");
    if (query.next()) {
        index1 = query.value(0).toInt() + 1;
    } else {
        index1 = 1;
    }

    query.exec("SELECT MAX(id) FROM Times2");
    if (query.next()) {
        index2 = query.value(0).toInt() + 1;
    } else {
        index2 = 1;
    }

    query.exec("SELECT MAX(id) FROM Times3");
    if (query.next()) {
        index3 = query.value(0).toInt() + 1;
    } else {
        index3 = 1;
    }

    if (!query.exec()) {
        qDebug() << "SQL 执行失败：" << query.lastError().text();
        return;
    }

    db.commit();
    db.close();
}







